/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormAberturaChamados.java
 *
 * Created on 06/12/2011, 01:13:30
 */

package sistemachamados.view;

import classes.*;
import javax.swing.*;
import java.util.*;
import javax.swing.table.DefaultTableModel;


/**
 *
 * @author Cleber Lopes
 */
public class FormEstados extends javax.swing.JInternalFrame {

    private Usuario usuarioLogado;

    public FormEstados(Usuario usuarioLogado) {
        initComponents();
        this.usuarioLogado = usuarioLogado;

    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        bntPesquisar = new javax.swing.JButton();
        btnLimpar = new javax.swing.JButton();
        cmbEstado = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        btnExcluir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblEstado = new javax.swing.JTable();
        btnIncluir = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtEstado = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        btnCancelar = new javax.swing.JButton();
        txtUF = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setBorder(null);
        setClosable(true);
        setFrameIcon(null);
        setInheritsPopupMenu(true);
        setMinimumSize(new java.awt.Dimension(990, 470));
        setPreferredSize(new java.awt.Dimension(990, 470));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });
        getContentPane().setLayout(null);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "FILTROS DE PESQUISA", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Showcard Gothic", 0, 16))); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(FormEstados.class);
        jPanel1.setFont(resourceMap.getFont("jPanel1.font")); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setOpaque(false);

        jLabel1.setFont(new java.awt.Font("Gautami", 3, 16));
        jLabel1.setText("Estado");
        jLabel1.setName("jLabel1"); // NOI18N

        bntPesquisar.setFont(new java.awt.Font("Berlin Sans FB Demi", 0, 14)); // NOI18N
        bntPesquisar.setText("Pesquisar");
        bntPesquisar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        bntPesquisar.setName("bntPesquisar"); // NOI18N
        bntPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntPesquisarActionPerformed(evt);
            }
        });

        btnLimpar.setFont(new java.awt.Font("Berlin Sans FB Demi", 0, 14)); // NOI18N
        btnLimpar.setText("Limpar");
        btnLimpar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        btnLimpar.setName("btnLimpar"); // NOI18N
        btnLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimparActionPerformed(evt);
            }
        });

        cmbEstado.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
        cmbEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todos" }));
        cmbEstado.setName("cmbEstado"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 413, Short.MAX_VALUE)
                .addComponent(bntPesquisar)
                .addGap(18, 18, 18)
                .addComponent(btnLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(45, 45, 45))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(17, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(btnLimpar)
                    .addComponent(bntPesquisar)
                    .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        getContentPane().add(jPanel1);
        jPanel1.setBounds(10, 20, 960, 80);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "ESTADOS", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Showcard Gothic", 0, 16))); // NOI18N
        jPanel2.setFont(new java.awt.Font("Showcard Gothic", 0, 16));
        jPanel2.setName("jPanel2"); // NOI18N
        jPanel2.setOpaque(false);
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnExcluir.setFont(new java.awt.Font("Berlin Sans FB Demi", 0, 16)); // NOI18N
        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sistemachamados/view/resources/Xicon.png"))); // NOI18N
        btnExcluir.setText("Excluir");
        btnExcluir.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        btnExcluir.setName("btnExcluir"); // NOI18N
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });
        jPanel2.add(btnExcluir, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 160, 110, -1));

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblEstado.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        tblEstado.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tblEstado.setCellSelectionEnabled(true);
        tblEstado.setName("tblEstado"); // NOI18N
        tblEstado.getTableHeader().setResizingAllowed(false);
        tblEstado.getTableHeader().setReorderingAllowed(false);
        tblEstado.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblEstadoMouseClicked(evt);
            }
        });
        tblEstado.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblEstadoKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(tblEstado);

        jPanel2.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 40, 720, 100));

        btnIncluir.setFont(new java.awt.Font("Berlin Sans FB Demi", 0, 16)); // NOI18N
        btnIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sistemachamados/view/resources/ViconUsado.png"))); // NOI18N
        btnIncluir.setText("Incluir");
        btnIncluir.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        btnIncluir.setName("btnIncluir"); // NOI18N
        btnIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncluirActionPerformed(evt);
            }
        });
        jPanel2.add(btnIncluir, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 160, 110, -1));

        btnAlterar.setFont(new java.awt.Font("Berlin Sans FB Demi", 0, 16)); // NOI18N
        btnAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sistemachamados/view/resources/!icon.png"))); // NOI18N
        btnAlterar.setText("Alterar");
        btnAlterar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        btnAlterar.setName("btnAlterar"); // NOI18N
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        jPanel2.add(btnAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 160, 110, -1));

        getContentPane().add(jPanel2);
        jPanel2.setBounds(10, 104, 960, 210);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "INCLUIR / ALTERAR ESTADO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Showcard Gothic", 0, 16))); // NOI18N
        jPanel3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 24)); // NOI18N
        jPanel3.setName("jPanel3"); // NOI18N
        jPanel3.setOpaque(false);

        jLabel3.setFont(new java.awt.Font("Gautami", 3, 16));
        jLabel3.setText("Estado");
        jLabel3.setName("jLabel3"); // NOI18N

        txtEstado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtEstado.setName("txtEstado"); // NOI18N

        jLabel4.setFont(new java.awt.Font("Gautami", 3, 16));
        jLabel4.setText("UF");
        jLabel4.setName("jLabel4"); // NOI18N

        btnCancelar.setFont(new java.awt.Font("Berlin Sans FB Demi", 0, 14)); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        btnCancelar.setName("btnCancelar"); // NOI18N
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        txtUF.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtUF.setName("txtUF"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(47, 47, 47)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtUF, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 152, Short.MAX_VALUE)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(167, 167, 167))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap(18, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(btnCancelar)
                    .addComponent(jLabel4)
                    .addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        getContentPane().add(jPanel3);
        jPanel3.setBounds(10, 320, 960, 80);

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sistemachamados/view/resources/FORM PRINCIPAL (FUNDOPANEL).png"))); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N
        getContentPane().add(jLabel5);
        jLabel5.setBounds(0, 0, 980, 460);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        btnIncluir.setEnabled(false);
        btnAlterar.setEnabled(false);
        btnExcluir.setEnabled(false);
        atualizarEstado();
        verificaPermissao();
        preencherCombo();
    }//GEN-LAST:event_formComponentShown

    private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncluirActionPerformed
        Estado estado  = new Estado();
        if (txtEstado.getText().equals(""))
        {
            JOptionPane.showMessageDialog(null, "Preencha o Estado.");
        }else {
            if (txtUF.getText().equals(""))
            {
                JOptionPane.showMessageDialog(null, "Preencha a Sigla.");
            }else{
                estado.setDescr(txtEstado.getText());
                estado.setSigla(txtUF.getText());
                if((estado.salvar(usuarioLogado))==true){
                    JOptionPane.showMessageDialog(null, "Inclusão bem sucedida.");
                }else{
                    JOptionPane.showMessageDialog(null, "Inclusão mal sucedida, verifique se o UF já existe!");
                }
                limparCampos();
                preencherCombo();

            }
        }
    }//GEN-LAST:event_btnIncluirActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        Estado estado = new Estado();
        if (txtEstado.getText().equals(""))
        {
            JOptionPane.showMessageDialog(null, "Selecione o Estado.");
        }else {
            estado.setDescr(txtEstado.getText());
                estado.setSigla(txtUF.getText());
                if((estado.alterar(usuarioLogado))==true){
                    JOptionPane.showMessageDialog(null, "Alteração bem sucedida.");
                }else{
                    JOptionPane.showMessageDialog(null, "Alteração mal sucedida, verifique se o Estado foi selecionado da tabela, ou se o Estado possui Cidades relacionadas!");
                }
                limparCampos();
                preencherCombo();
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void tblEstadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblEstadoKeyPressed
        preecherCampos();
    }//GEN-LAST:event_tblEstadoKeyPressed

    private void tblEstadoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblEstadoMouseClicked
        preecherCampos();
    }//GEN-LAST:event_tblEstadoMouseClicked

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
         if (txtUF.getText().equals(""))
        {
            JOptionPane.showMessageDialog(null, "Selecione uma Categoria.");
        }else{

            if(tblEstado.getRowCount() > 0){
                String sigla = (tblEstado.getValueAt(tblEstado.getSelectedRow(), 1).toString());
                Estado estado = new Estado();
                estado.setSigla(sigla);
                if((estado.deletar())==true){
                    JOptionPane.showMessageDialog(null, "Exclusão bem sucedida.");
                }else{
                    JOptionPane.showMessageDialog(null, "Exclusão mal sucedida, verifique se o Estado foi selecionado da tabela, ou se o Estado possui Cidades relacionadas!");
                }
                limparCampos();
                atualizarEstado();
            }
        }
    }//GEN-LAST:event_btnExcluirActionPerformed
    //---------Realiza a pesquisa de somente o item selecionado no combobox
    private void bntPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntPesquisarActionPerformed
        if(cmbEstado.getItemCount() > 0)
        {
            String estado = (cmbEstado.getSelectedItem().toString());
            DefaultTableModel modelo = new DefaultTableModel();
            tblEstado.setModel(modelo);
            modelo.addColumn("Descrição");
            modelo.addColumn("Sigla");
            ArrayList<Estado> listEstados =Estado.pesquisar(estado);
            for(int i=0; i < listEstados.size();i++)
            {
                Object[] linha = new Object[2];
                linha[0]=listEstados.get(i).getDescr();
                linha[1]=listEstados.get(i).getSigla();
                modelo.insertRow(modelo.getRowCount(), linha);
            }
        }
    }//GEN-LAST:event_bntPesquisarActionPerformed

    private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed
        limparCampos();
    }//GEN-LAST:event_btnLimparActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
       limparCampos();
    }//GEN-LAST:event_btnCancelarActionPerformed

    //---------Verifica quais permissões o usuário possui e habilita aquelas permitidas
    public void verificaPermissao()
    {
        ArrayList<Acesso> listPermissao = usuarioLogado.getListAcessos();

      if(listPermissao != null){
        for (int i = 0; i < listPermissao.size(); i++) {
            String descr_pemissao=listPermissao.get(i).getDescr();

            if( descr_pemissao.equals("Incluir") ){
                btnIncluir.setEnabled(true);
            }
            if( descr_pemissao.equals("Alterar") ){
                btnAlterar.setEnabled(true);
            }
            if( descr_pemissao.equals("Excluir") ){
                btnExcluir.setEnabled(true);
            }
        }
      }
    }

    //---------Atualiza a tabela de Estados Cadastrados
    private void atualizarEstado(){
        DefaultTableModel modelo = new DefaultTableModel();
        tblEstado.setModel(modelo);
        modelo.addColumn("Descrição");
        modelo.addColumn("Sigla");
        ArrayList<Estado> listEstados =Estado.selecionar();
        for(int i=0; i < listEstados.size();i++)
        {
            Object[] linha = new Object[2];
            linha[0]=listEstados.get(i).getDescr();
            linha[1]=listEstados.get(i).getSigla();
            modelo.insertRow(modelo.getRowCount(), linha);
        }
    }

    //---------Limpa os campos e atualiza a tabela
    public void limparCampos(){
        atualizarEstado();
        txtEstado.setText("");
        txtUF.setText("");
        cmbEstado.setSelectedIndex(0);
    }

    //---------Preenche a tabela com o valor do item selecionado
    public void preecherCampos(){
        if(tblEstado.getRowCount() > 0){
           String descrEstado = tblEstado.getValueAt(tblEstado.getSelectedRow(), 0).toString();
           String siglaEstado = tblEstado.getValueAt(tblEstado.getSelectedRow(), 1).toString();

           txtEstado.setText(descrEstado);
           txtUF.setText(siglaEstado);
        }
    }

    //---------Preenche a combobox com os estados cadastrados
    private void preencherCombo(){
       
        Estado estado = new Estado();
        ArrayList<Estado> listEstado = estado.selecionar() ;

        if(listEstado != null)
        {
            cmbEstado.setModel(new DefaultComboBoxModel(listEstado.toArray()));
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Falha no carregamento dos Estados.", "Verifique se existem Estados cadastrados", JOptionPane.WARNING_MESSAGE);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bntPesquisar;
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnIncluir;
    private javax.swing.JButton btnLimpar;
    private javax.swing.JComboBox cmbEstado;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblEstado;
    private javax.swing.JTextField txtEstado;
    private javax.swing.JTextField txtUF;
    // End of variables declaration//GEN-END:variables

}
